package com.hn.common.utils.ding;

import cn.hutool.core.date.DateUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiWorkrecordAddRequest;
import com.dingtalk.api.request.OapiWorkrecordUpdateRequest;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiProcessWorkrecordTaskQueryResponse;
import com.dingtalk.api.response.OapiWorkrecordAddResponse;
import com.dingtalk.api.response.OapiWorkrecordUpdateResponse;
import com.hn.common.exception.BusinessException;
import com.hn.utils.dingtalk.exception.DingTalkException;
import com.taobao.api.ApiException;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 消息通知接口
 *
 * @author admin
 */
public class DingNoticeUtil {

    private static final String MESSAGE_URL = "http://xunjian.hntool.vip:8080/h5/#/safetyInspection?id=";

    public static void main(String[] args) throws ApiException {
//        sendTaskMsg("050210155830215836", 48 , "网点自查任务","网点自查",
//                "高新区");
        updateWorkRecord("050210155830215836","record177c35517fdd4a7fec310d1747aa9088");
    }

    /**
     * 审批通过或者拒绝 给 申请人发送消息
     */
    public static String sendTaskMsg(String userids, Integer orderId, String taskName,
                                        String taskTypeName, String branchName) {
        List<OapiWorkrecordAddRequest.FormItemVo> forms = new ArrayList<>();
        OapiWorkrecordAddRequest.FormItemVo form = new OapiWorkrecordAddRequest.FormItemVo();
        form.setTitle("任务名称：");
        form.setContent(taskName);
        forms.add(form);

        form = new OapiWorkrecordAddRequest.FormItemVo();
        form.setTitle("任务类型：");
        form.setContent(taskTypeName);
        forms.add(form);

        form = new OapiWorkrecordAddRequest.FormItemVo();
        form.setTitle("巡检网点：");
        form.setContent(branchName);
        forms.add(form);

        String messageUrl = MESSAGE_URL + orderId;
        String title = "新任务";
        return sendWorkRecord(userids, title,forms, messageUrl);
    }


    public static void send(String userids, List<OapiMessageCorpconversationAsyncsendV2Request.Form> forms,
                            String content, String messageUrl) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");

        OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
        request.setUseridList(userids);
        request.setAgentId(Long.valueOf(DingConstant.AGENTID));
        request.setToAllUser(false);

        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
        msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
        msg.getOa().getHead().setText("钉牛智慧教育");
        OapiMessageCorpconversationAsyncsendV2Request.Body body = new OapiMessageCorpconversationAsyncsendV2Request.Body();

        body.setForm(forms);

        msg.getOa().setBody(body);
        msg.getOa().getBody().setContent(content);
        msg.getOa().setMessageUrl(messageUrl);
        msg.getOa().setPcMessageUrl(messageUrl);

        msg.setMsgtype("oa");
        request.setMsg(msg);

        try {
            OapiMessageCorpconversationAsyncsendV2Response response = client.execute(request, AccessTokenUtil.getToken());
            System.out.println(response.getErrmsg());
        } catch (ApiException e) {
            throw new BusinessException(e.getErrMsg());
        }
    }

    /**
     *  发送待办
     * @return 钉钉任务记录id
     */
    public static String sendWorkRecord(String userid, String title,List<OapiWorkrecordAddRequest.FormItemVo> forms, String url){
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/workrecord/add");
        OapiWorkrecordAddRequest req = new OapiWorkrecordAddRequest();
        req.setUserid(userid);
        req.setCreateTime(DateUtil.date().getTime());
        req.setTitle(title);
        req.setUrl(url);
//        req.setPcUrl("https://oa.dingtalk.com");
//        List<OapiWorkrecordAddRequest.FormItemVo> list2 = new ArrayList<>();
//        OapiWorkrecordAddRequest.FormItemVo obj3 = new OapiWorkrecordAddRequest.FormItemVo();
//        list2.add(obj3);
//        obj3.setTitle("新人学习2");
//        obj3.setContent("产品学习");
        req.setFormItemList(forms);
        // 发起人的userid。
        // req.setOriginatorUserId("manager7078");
        // 待办来源名称
        req.setSourceName("巡检钉钉");
        // 待办的PC打开方式: 2：在PC端打开 4：在浏览器打开
        // req.setPcOpenType(2L);
        // 外部业务ID，建议带上业务方来源字段，防止与其他业务方冲突。
        // req.setBizId("1112");
        try {
            OapiWorkrecordAddResponse rsp = client.execute(req, AccessTokenUtil.getToken());
            System.out.println(rsp.getRecordId());
            return rsp.getRecordId();
        } catch (ApiException e) {
            throw new DingTalkException(e.getErrMsg());
        }
    }

    /**
     * 完成待办
     * @param userid 用户id
     * @param recordId 钉钉待办任务记录id
     */
    public static void updateWorkRecord(String userid,String recordId){
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/workrecord/update");
        OapiWorkrecordUpdateRequest req = new OapiWorkrecordUpdateRequest();
        req.setUserid(userid);
        req.setRecordId(recordId);
        try {
            OapiWorkrecordUpdateResponse rsp = client.execute(req, AccessTokenUtil.getToken());
            System.out.println(rsp.getErrmsg());
        } catch (ApiException e) {
            throw new DingTalkException(e.getErrMsg());
        }
    }

}
